import { SyncHook, AsyncParallelHook } from 'tapable'
class List {
	getRoutes() {}
}
class Car {
	constructor() {
		this.hooks = {
			accelerate: new SyncHook(['newSpeed']),
			calculateRoutes: new AsyncParallelHook([
				'source',
				'target',
				'routesList',
			]),
		}
	}

	setSpeed(newSpeed) {
		// following call returns undefined even when you returned values
		// 触发事件
		this.hooks.accelerate.call(newSpeed)
	}

	async useNavigationSystemPromise(source, target) {
		const routesList = new List()
		return this.hooks.calculateRoutes
			.promise(source, target, routesList)
			.then((res) => {
				// res is undefined for AsyncParallelHook
				// 最后执行到这里
				console.log('useNavigationSystemPromise')
				return routesList.getRoutes()
			})
	}

	useNavigationSystemAsync(source, target, callback) {
		const routesList = new List()
		this.hooks.calculateRoutes.callAsync(
			source,
			target,
			routesList,
			(err) => {
				if (err) return callback(err)
				callback(null, routesList.getRoutes())
			}
		)
	}
}
// 注册
const car = new Car()
car.hooks.accelerate.tap('testAccelerate', (speed) => {
	console.log('testAccelerate :>>', speed)
})
car.hooks.calculateRoutes.tapPromise(
	'testCalculateRoutesPromsie',
	(source, taget) => {
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				console.log('testCalculateRoutesPromsie', source, taget)
				resolve()
			}, 500)
		})
	}
)
// 触发
car.setSpeed(10)
car.useNavigationSystemPromise([1, 2, 3], 3)
